<template>
  <div ref="echartsRef" class="w-full h-full"></div>
</template>

<script setup>
  import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
  import * as echarts from 'echarts'
  import useResize from '@/utils/resize'
  import tdTheme from './theme.json' // 引入默认主题

  const props = defineProps({ option: Object })

  const echartsRef = ref(null)
  let echartsInstance = ref(null)

  onMounted(() => {
    echarts.registerTheme('tdTheme', tdTheme) // 覆盖默认主题
    initChart()
  })

  watch(
    () => props.option,
    () => {
      initChart()
    },
  )

  onBeforeUnmount(() => {
    if (!echartsInstance.value) {
      return
    }
    echartsInstance.value.dispose()
    echartsInstance.value = null
  })

  useResize(echartsInstance)

  const initChart = () => {
    echartsInstance.value = echarts.init(echartsRef.value, 'tdTheme', {
      renderer: 'canvas',
    })
    echartsInstance.value.setOption(props.option)
  }
</script>
